package br.com.intelsys.basics.spring;

import java.lang.reflect.InvocationTargetException;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import br.com.intelsys.basics.bfactory.FactoryManager;
import br.com.intelsys.basics.bfactory.SpringMvc;

@Component
@Scope("request")
public class RequestInfoArgumentResolver implements WebArgumentResolver {

	private Class<WebReqGeneric> webReqClass;
	@SuppressWarnings("rawtypes")
	private static final Class[] REPLICATE_CONSTRUCTOR_PARAMS = new Class[] { NativeWebRequest.class };

	@Override
	public Object resolveArgument(MethodParameter parameter,
			NativeWebRequest webRequest) throws Exception {
		checkWebReqClass();
		if (parameter.getParameterType().equals(webReqClass)) {
			return loadWebReq(webRequest);
		}
		return WebArgumentResolver.UNRESOLVED;
	}

	public void checkWebReqClass() {
		if (webReqClass == null) {
			SpringMvc s = FactoryManager.getInstance().getSpringMvc();
			if (s != null) {
				webReqClass = FactoryManager.getInstance().getSpringMvc()
						.getWebReqClass();
			} else {
				webReqClass = WebReqGeneric.class;
			}
		}
	}

	public WebReqGeneric loadWebReq(NativeWebRequest webRequest) {
		WebReqGeneric wr;
		try {
			wr = webReqClass.getDeclaredConstructor(
					REPLICATE_CONSTRUCTOR_PARAMS).newInstance(webRequest);
		} catch (InstantiationException e) {
			e.printStackTrace();
			wr = null;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			wr = null;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			wr = null;
		} catch (SecurityException e) {
			e.printStackTrace();
			wr = null;
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			wr = null;
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			wr = null;
		}
		return wr;
	}

}
